<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="ExamPwdForm">
          <a-row>
            <a-col :span="24">
              <a-form-item label="题库" v-bind="validateInfos.bankId" id="ExamPwdForm-bankId" name="bankId">
                <a-select
                  placeholder="请选择题库"
                  ref="select"
                  v-model:value="formData.bankId"
                >
                  <a-select-option v-for="item in res.seldata" :key="item.value" :value="item.value">{{ item.label }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="到期时间" v-bind="validateInfos.maturityTime" id="ExamPwdForm-maturityTime" name="maturityTime">
                <a-date-picker placeholder="请选择到期时间" v-model:value="formData.maturityTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="首次考试开始时间" id="ExamPwdForm-startTime" name="startTime">
                <a-date-picker placeholder="请选择开始时间" v-model:value="formData.startTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="二次考试开始时间" id="ExamPwdForm-startTimeTwo" name="startTimeTwo">
                <a-date-picker placeholder="请选择开始时间" v-model:value="formData.startTimeTwo" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="登陆时长（分钟）" v-bind="validateInfos.other" id="ExamPwdForm-other" name="other">
                <a-input v-model:value="formData.other" placeholder="请输入登陆时长(分钟)" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="考试时长" v-bind="validateInfos.time" id="ExamPwdForm-time" name="time">
                <a-input v-model:value="formData.time" placeholder="请输入考试时长(分钟)" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="出题是否随机" v-bind="validateInfos.isrAndom" id="ExamPwdForm-isrAndom" name="isrAndom">
                <a-radio-group v-model:value="formData.isrAndom">
                  <a-radio :value="0">不开启</a-radio>
                  <a-radio :value="1">开启</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            
            <a-col :span="24">
              <a-form-item label="六位数口令码(唯一标识)" v-bind="validateInfos.passcode" id="ExamPwdForm-passcode" name="passcode">
                <a-input v-model:value="formData.passcode" placeholder="请输入六位数口令码 (唯一标识)" style="width: 87%;" allow-clear />
                <a-button @click="getpwds">获取</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted, watch } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate, listtiku, getpwd } from '../ExamPwd.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import dayjs from 'dayjs';
  
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    formBpm: { type: Boolean, default: true }
  });
  
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    bankId: undefined,
    maturityTime: '',
    startTime: '',
    stopTime: '',
    time: '',
    startTimeTwo: '',
    stopTimeTwo: '',
    passcode: '',
    passcount: 1,
    isStart: 0,
    other: '', // 登錄時長字段
    isrAndom: 1, // 出題是否隨機，默認不開啟
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  
  // 計算考試次數和是否開啟第二次考試
  const computedExamSettings = computed(() => {
    const hasSecondExam = !!formData.startTimeTwo;
    return {
      passcount: hasSecondExam ? 2 : 1,
      isStart: hasSecondExam ? 1 : 0
    };
  });
  
  // 計算登錄結束時間
  const calculateLoginEndTime = (startTime: string, loginTime: number) => {
    if (!startTime || !loginTime) return '';
    const start = dayjs(startTime);
    const end = start.add(loginTime, 'minute');
    return end.format('YYYY-MM-DD HH:mm:ss');
  };
  
  // 監聽登錄時長變化，自動計算結束時間
  watch(() => [formData.startTime, formData.other], () => {
    if (formData.startTime && formData.other) {
      formData.stopTime = calculateLoginEndTime(formData.startTime, parseInt(formData.other));
    }
  });
  
  // 監聽二次考試開始時間變化，自動計算結束時間
  watch(() => [formData.startTimeTwo, formData.other], () => {
    if (formData.startTimeTwo && formData.other) {
      formData.stopTimeTwo = calculateLoginEndTime(formData.startTimeTwo, parseInt(formData.other));
    }
  });
  
  // 表单验证
  const validatorRules = reactive({
    bankId: [{ required: true, message: '请输入题库ID!' }],
    maturityTime: [{ required: true, message: '请输入到期时间!' }],
    time: [{ required: true, message: '请输入时长!' }],
    other: [{ required: true, message: '请输入登陆时长!' }],
    passcode: [{ required: true, message: '请输入六位数口令码 (唯一标识)!' }],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });

  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    console.log(record, "record")
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if (record.hasOwnProperty(key)) {
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    console.log(model, "modelmodelmodelmodel")
    
    // 根據是否有二次考試時間來決定參數結構
    const hasSecondExam = !!model.startTimeTwo;
    
    let submitData;
    
    if (hasSecondExam) {
      // 有二次考試時間，使用 timeList 數組格式
      submitData = {
        id: model.id || '',
        bankId: model.bankId,
        maturityTime: model.maturityTime,
        passcode: model.passcode,
        time: model.time,
        other: model.other, // 添加 other 字段
        isrAndom: model.isrAndom, // 添加 isrAndom 字段
        passcount: 2,
        isStart: 1,
        timeList: JSON.stringify([{
          startTime: model.startTime,
          stopTime: model.stopTime,
        }, {
          startTime: model.startTimeTwo,
          stopTime: model.stopTimeTwo,
        }])
      };
    } else {
      // 沒有二次考試時間，使用單個時間字段格式
      submitData = {
        id: model.id || '',
        bankId: model.bankId,
        maturityTime: model.maturityTime,
        startTime: model.startTime,
        stopTime: model.stopTime,
        time: model.time,
        startTimeTwo: '',
        stopTimeTwo: '',
        passcode: model.passcode,
        other: model.other, // 添加 other 字段
        isrAndom: model.isrAndom, // 添加 isrAndom 字段
        passcount: 1,
        isStart: 0
      };
    }
    
    console.log('提交的數據:', submitData);
    await saveOrUpdate(submitData, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }
  const res = reactive({
    seldata: []
  })
  const getpwds = async () => {
    const res = await getpwd('')
    formData.passcode = res
  }
  onMounted(async () => {
    res.seldata = []
    const ress = await listtiku('?column=createTime&order=desc&pageNo=1&pageSize=10')
    console.log(ress.records, "listtiku")
          if (ress.records.length > 0) {
        ress.records.forEach((item: any) => {
          res.seldata.push({
            label: item.name,
            value: item.id
          })
        })
      }
  })

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
